package com.easypan.Service.impl;

import com.easypan.Service.UserService;
import com.easypan.component.redisComponent;
import com.easypan.entity.constants.Constants;
import com.easypan.entity.dto.SessionwebUserDto;
import com.easypan.entity.dto.UserSpaceDto;
import com.easypan.entity.po.UserInfo;
import com.easypan.entity.query.SimplePage;
import com.easypan.entity.query.UserInfoQuery;
import com.easypan.entity.vo.PaginationResultVO;
import com.easypan.entity.vo.R;
import com.easypan.enums.PageSize;
import com.easypan.mapper.EmailMapper;
import com.easypan.mapper.UserMapper;

import com.github.pagehelper.PageHelper;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Service
public class Userservice implements UserService {
   @Autowired
 private    UserMapper userMapper;
    @Autowired
    private EmailMapper emailMapper;
@Value("${admin.emails:}")
private  String adminEmails;
@Autowired
private redisComponent redisComponent;
    @Override
    public R zuce(HttpServletRequest req, String email, String nickName, String password, String password1, String emailCode, String checkCode) {
       ///1.比对 两个验证码是否正确
        HttpSession session= req.getSession();
        String attribute = (String) session.getAttribute(Constants.CHECK_CODE_KEY);
        if(attribute==null || !attribute.equalsIgnoreCase(checkCode))
        {
         return    R.error("验证码错误");
        }
    ///2.验证码正确了--判断邮箱验证码 --通过邮箱ID 查询验证码

        ///ps--修改为 直接拿出statan邮箱 如果超时置1

        String chaxunid = emailMapper.chaxunid(email);
        if(chaxunid==null || !chaxunid.equalsIgnoreCase(emailCode))
        {
            return  R.error("邮箱验证码错误");
        }
        ///3.查询名字是否重复
        int i = userMapper.selectByname(nickName);
        if(i>0)
        {
            return  R.error("你的名字重复啦");
        }
        //现在就是可以入数据库了
        UserInfo userInfo=new UserInfo();
        userInfo.setNickName(nickName);
        userInfo.setEmail(email);

        ///MD5哈希加密
        String encryptedString = DigestUtils.md5Hex(password);
        userInfo.setPassword(encryptedString);
        userInfo.setJoinTime(new Date());
        userInfo.setStatus(0);
        userInfo.setTotalSpace((10*1024*1024l));
        userMapper.insetuser(userInfo);
        return R.success("注册成功");

        //too 将邮箱更改为已使用
    }

    @Override
    public R dl(String email, String password, String checkCode, HttpServletRequest req) {
       ///判断账号密码 是否能对的上ID --先判断验证码
     HttpSession httpSession=req.getSession();
        String attribute = (String) httpSession.getAttribute(Constants.CHECK_CODE_KEY);
       if(attribute==null || !attribute.equalsIgnoreCase(checkCode))
       {
           return  R.error("验证码出错");
       }
       ///1.根据 账号 和密码去匹配是否有对象 如果有就返回--返回对象
        UserInfo userInfo = userMapper.selectByzhmm(email, password);
if(userInfo==null)
{
    return R.error("账号密码错误");
}
if(userInfo.getStatus()==1)
{
    return R.error("账号被禁用");
}
        SessionwebUserDto sessionwebUserDto=new SessionwebUserDto();
        sessionwebUserDto.setNickName(userInfo.getNickName());
        sessionwebUserDto.setUserId(Integer.parseInt(userInfo.getUserId()));
        sessionwebUserDto.setTotalSpace(userInfo.getTotalSpace());
        if(ArrayUtils.contains(adminEmails.split(","),email))
        {
            //如果这些包含我的邮箱就给超级
            sessionwebUserDto.setAdmin(true);
        }else {
            sessionwebUserDto.setAdmin(false);
        }


        return R.success(sessionwebUserDto);
    }

    @Override
    public R xgmm(String email, String password, String checkCode, String emailCode,HttpServletRequest request) {
        ///1.判断验证码
        HttpSession session=request.getSession();
        String attribute = (String) session.getAttribute(Constants.CHECK_CODE_KEY);
        if(attribute==null || !attribute.equalsIgnoreCase(checkCode))
        {
            return R.error("验证码错误");
        }

        ///2.判断邮箱验证码
       //根据邮箱字段从中拿出code
        String chaxunid = emailMapper.chaxunid(email);
        ///3.判断
        if(chaxunid==null || !chaxunid.equalsIgnoreCase(emailCode))
        {
            return R.error("邮箱验证码错误");
        }
         ///都成功 修改密码
        String encryptedString = DigestUtils.md5Hex(password);
        userMapper.updatatpassword(encryptedString,email);


        return R.success("修改成功");
    }

    @Override
    public void qqtxqk(UserInfo userInfo) {
        userMapper.qqtxqk(userInfo);
    }

    @Override
    public R getUserSpace(HttpSession session) {
        UserSpaceDto userSpaceDto=new UserSpaceDto();
        ///这里从redis中拿 --再判断为空 为空就是redis没有

        SessionwebUserDto sessionKey = (SessionwebUserDto) session.getAttribute("session_key");

        if(sessionKey==null)
        {
            return R.error("出现未知错误");
        }
        userSpaceDto= redisComponent.getUserSpaceUsekj(sessionKey.getUserId());
        if(userSpaceDto.getUseSpace()==null||userSpaceDto.getTotalSpace()==null)
        {
            //返回当前文件总大小和我们的总容量
            //根据suerid +状态 查询所有文件 -得出已经使用容量\

            Long l = userMapper.selectUseSpace(sessionKey.getUserId());
            if(l==null)
            {
                l= 0L;
            }
           userSpaceDto.setUseSpace(l);
            userSpaceDto.setTotalSpace(sessionKey.getTotalSpace());
            // 一个是插入数据库中 userinfo ->还有一个是插入redis中
            redisComponent.saveUserSpace(String.valueOf(sessionKey.getUserId()),userSpaceDto);
            userMapper.updatauser(sessionKey.getUserId(),userSpaceDto);
          //无需sql-
        }
        return R.success(userSpaceDto);
    }

    @Override
    public Integer findCountByParam(UserInfoQuery param) {
        return null;
    }

    @Override
    public List<UserInfo> findListByParam(UserInfoQuery param) {
        return null;
    }


    @Override

    public PaginationResultVO<UserInfo> loadFileList(SessionwebUserDto webUserDto, UserInfoQuery userInfoQuery) {


        int count = userMapper.selectCount();
        userInfoQuery.setOrderBy("join_time desc");
        int pageSize = userInfoQuery.getPageSize() == null ? PageSize.SIZE15.getSize() : userInfoQuery.getPageSize();

        SimplePage page = new SimplePage(userInfoQuery.getPageNo(), count, pageSize);


        userInfoQuery.setSimplePage(page);
        List<UserInfo> list = userMapper.selectList(userInfoQuery);
        PaginationResultVO<UserInfo> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
        //2、获取分页查询结果列表

        return result;
    }
}
